package smartcarpool.smartspaceservice;

import android.app.PendingIntent;
import android.content.Intent;
import android.util.Log;
import sofia_kp.KPICore;

import java.util.Vector;

import static smartcarpool.smartspaceservice.SmartSpaceService.*;


public class SmartSpaceQuery implements Runnable {

    private SmartSpaceService parent;
    private String HOST;
	private int PORT;
	private String SPACE_NAME;
	private Vector<Vector<String>> tripleVector;
    private PendingIntent pendingIntent;

	public SmartSpaceQuery(String HOST, int PORT, String SPACE_NAME, Vector<Vector<String>> tripleVectorToQuery, PendingIntent pendingIntent, SmartSpaceService parent) {
		this.HOST = HOST;
		this.PORT = PORT;
		this.SPACE_NAME = SPACE_NAME;
		this.tripleVector = tripleVectorToQuery;
        this.pendingIntent = pendingIntent;
        this.parent = parent;
	}

	@Override
	public void run() {
        Vector<Vector<String>> result_vector = new Vector<Vector<String>>();
        Log.d("SmartSpaceQuery "," Try to query triple");
        try {
            KPICore smartSpace = new KPICore(this.HOST, this.PORT, this.SPACE_NAME);
            String joinResult = smartSpace.join();
            if (joinResult != null){
                if (joinResult != null || smartSpace.xmlTools.isJoinConfirmed(joinResult)) {
                    String answer = smartSpace.queryRDF(tripleVector);
                    if (smartSpace.xmlTools.isQueryConfirmed(answer)){
                        //Log.d("SmartSpaceQuery raw_result: ", answer);
                        result_vector = smartSpace.xmlTools.getQueryTriple(answer);
                        pendingIntent.send(parent.getApplicationContext(), RESULT_SUCCESS_QUERY, new Intent().putExtra(SMART_SPACE_QUERY_ANSWER,new TripleList(result_vector)));
                        Log.d("SmartSpaceQuery "," Information has been queried");
                    } else {
                        pendingIntent.send(RESULT_FAILURE_QUERY);
                    }
                } else {
                    pendingIntent.send(RESULT_FAILURE_JOIN);
                }
            } else {
                pendingIntent.send(RESULT_FAILURE_JOIN);
            }
            smartSpace.leave();
        } catch (PendingIntent.CanceledException e){
            Log.e("SmartSpaceQuery. Pending Intent Error, Canceled", e.toString());
            e.printStackTrace();
        } catch (Exception e){
            Log.e("SmartSpaceQuery. Error", e.toString() + " \nAdditional Information: \n"+
                "Queried triple: " + tripleVector.toString() + "\n" +
                "answer" + result_vector.toString());
            e.printStackTrace();
        }

	}
}
